<?php

namespace App\Http\Controllers\V1;

use App\Http\Requests\UserAddressRequest;
use App\Models\MemberAddress;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AddressController extends Controller
{
    /**
     * 获取我的地址列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        return $this->success($request->user()->addresses);
    }

    /**
     * 添加用户地址
     * @param UserAddressRequest $request
     * @return mixed
     */
    public function store(UserAddressRequest $request)
    {
        $user = $request->user();

        if($request->has('vi'))
        {
            $miniProgram = \Wechat::miniProgram();
            $iv = $request->input('iv','');
            $encryptData = $request->input('encryptedData','');
            $request = $miniProgram->encryptor->decryptData($user->session_key, $iv, $encryptData);
        }

        $request->user()->addresses()->create($request->only([
            'province',
            'city',
            'district',
            'address',
            'contact_name',
            'contact_phone',
        ]));
        return $this->message('添加成功');
    }

    /**
     * 更新地址
     *
     * @param Request $request
     * @param $id
     * @return mixed
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function update(Request $request, $id)
    {
        $address = MemberAddress::findOrFail($id);
        $this->authorize('own', $address);
         $address->update($request->only([
            'province',
            'city',
            'district',
            'address',
            'contact_name',
            'contact_phone',
        ]));

        return $this->message('更新成功');
    }

    /**
     * 删除地址
     * @param $id
     * @return mixed
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function destroy($id)
    {
        $address = MemberAddress::findOrFail($id);

        $this->authorize('own', $address);

        $address->delete();

        return $this->message('删除成功');
    }
}
